import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:flutter/material.dart';
import 'package:inmotion_pro/extension/future_error_handler.dart';
import 'package:inmotion_pro/l10n/local.dart';
import 'package:inmotion_pro/pages/login_register/forms/phone_login_form.dart';
import 'package:inmotion_pro/pages/mixin/web_view_mixin.dart';
import 'package:inmotion_pro/routes/app_routes.dart';
import 'package:lx_widgets_library/lx_widgets_library.dart';
import '../../config/r.dart';
import '../models/user_model.dart';
import 'area_code/country_model.dart';
import 'controller.dart';
import 'forms/forget_pwd_form.dart';
import 'forms/email_login_form.dart';
import 'forms/email_register_form.dart';

// 登录页
class LoginRegisterView extends BaseGetView<LoginRegisterController>
    with WebViewMixin {
  LoginRegisterView({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      // Dark theme
      theme: ThemeData.dark().copyWith(
        scaffoldBackgroundColor: Colors.black,
        inputDecorationTheme: InputDecorationTheme(
          filled: true,
          fillColor: GrayColor.gray1,
          border: OutlineInputBorder(
            borderRadius: BorderRadius.circular(12),
            borderSide: BorderSide.none,
          ),
          contentPadding:
              const EdgeInsets.symmetric(horizontal: 16, vertical: 14),
        ),
        // 按钮主题
        textButtonTheme: TextButtonThemeData(
          style: TextButton.styleFrom(
            foregroundColor: Colors.white.withOpacity(0.8),
            padding: const EdgeInsets.symmetric(vertical: 0, horizontal: 4),
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(12),
            ),
            textStyle: const TextStyle(
              decoration: TextDecoration.underline,
              fontSize: 12,
            ),
          ),
        ),
      ),

      // 主体
      home: DismissKeyboardScaffold(
        resizeToAvoidBottomInset: false, // 防止键盘弹出时页面内容被顶起
        child: Scaffold(
          floatingActionButton: Padding(
            padding: EdgeInsets.only(top: 10.w),
            child: _guestLoginButton(context),
          ),
          floatingActionButtonLocation: FloatingActionButtonLocation.endTop,
          body: SingleChildScrollView(
            child: Container(
              padding: EdgeInsets.only(left: 24.w, right: 24.w),
              constraints: BoxConstraints(maxWidth: 400.w),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.center,
                children: [
                  // Logo and Title
                  Image.asset(
                    R.loginLogo,
                    width: 280.w,
                    height: 280.w,
                    fit: BoxFit.fitWidth,
                  ),

                  // Auth Card
                  Obx(
                    () => AnimatedSwitcher(
                      duration: const Duration(milliseconds: 300),
                      child: controller.state.authMode.value ==
                              AuthMode.emailLogin
                          ? EmailLoginForm(
                              key: const ValueKey('email_login'),
                              onSwitchAuthMode: _switchAuthMode,
                              loginWithEmailAction: (p0, p1) {
                                // p0: email, p1: password
                                // 使用邮箱+密码登录
                                controller.accountLogin(
                                  email: p0,
                                  password: p1,
                                );
                              },
                              thirdLoginAction: () {
                                controller.thirdLogin();
                              },
                            )
                          : controller.state.authMode.value ==
                                  AuthMode.phoneLogin
                              ? PhoneLoginForm(
                                  key: const ValueKey('phone_login'),
                                  onSwitchAuthMode: _switchAuthMode,
                                  sendVerificationCodeAction: (phone, p1) {
                                    // 发送验证码
                                    controller
                                        .requestVerificationCode(
                                          account:
                                              "${controller.state.formatAreaCode}$phone",
                                          platform: CodePlatform.phone,
                                          codeType: CodeType.login,
                                        )
                                        .then((value) => p1(value))
                                        .catchErrorHandler();
                                  },
                                  loginWithPhoneAction: (phone, code) {
                                    // 使用手机号+验证码登录
                                    controller.accountLogin(
                                      phone:
                                          "${controller.state.formatAreaCode}$phone",
                                      code: code,
                                    );
                                  },
                                  thirdLoginAction: () {
                                    controller.thirdLogin();
                                  },
                                  areaCode: controller.state.phoneCode.value,
                                  areaCodeOnTap: () {
                                    // 选择国家码
                                    Get.toNamed(AppRoutes.AREA_CODE,
                                            arguments: controller
                                                .state.phoneCode.value)
                                        ?.then((value) {
                                      if (value != null &&
                                          value is AreaCodeModel) {
                                        controller.state.phoneCode.value =
                                            value.phoneCode;
                                      }
                                    });
                                  },
                                )
                              : controller.state.authMode.value ==
                                      AuthMode.emailRegister
                                  ? EmailRegisterForm(
                                      key: const ValueKey('email_register'),
                                      onSwitchAuthMode: _switchAuthMode,
                                      sendVerificationCodeAction: (email, p1) {
                                        // 发送验证码，把邮箱传出去，同时外面传进来一个bool值表示是否发送成功
                                        controller
                                            .requestVerificationCode(
                                              account: email,
                                              platform: CodePlatform.email,
                                              codeType: CodeType.register,
                                            )
                                            .then((value) => p1(value))
                                            .catchErrorHandler();
                                      },
                                      registerWithEmailAction: (p0, p1, p2) {
                                        // p0: email, p1: password, p2: verificationCode
                                        controller.emailRegister(
                                          email: p0,
                                          password: p1,
                                          code: p2,
                                        );
                                      },
                                    )
                                  : ForgetPasswordForm(
                                      key: const ValueKey('forgot'),
                                      onSwitchAuthMode: _switchAuthMode,
                                      sendVerificationCodeAction: (email, p1) {
                                        // 发送验证码，把邮箱传出去，同时外面传进来一个bool值表示是否发送成功
                                        controller
                                            .requestVerificationCode(
                                              account: email,
                                              platform: CodePlatform.email,
                                              codeType: CodeType.resetPwd,
                                            )
                                            .then((value) => p1(value))
                                            .catchErrorHandler();
                                      },
                                      resetPasswordWithEmailAction:
                                          (p0, p1, p2) {
                                        // p0: email, p1: password, p2: verificationCode
                                        controller
                                            .emailResetPassword(
                                                email: p0,
                                                password: p1,
                                                code: p2)
                                            .then((resetSuccess) {
                                          if (resetSuccess) {
                                            // 重置成功，跳转到登录页面
                                            _switchAuthMode(
                                                AuthMode.emailLogin);
                                            Loading.showSuccess(
                                                local.update_password_success);
                                          } else {
                                            Loading.showError(
                                                local.update_password_failed);
                                          }
                                        }).catchErrorHandler();
                                      },
                                    ),
                    ),
                  ),
                  _buildPolicyText(),
                ],
              ),
            ),
          ),
        ),
      ),
    );
  }

  // 游客登录按钮
  Widget _guestLoginButton(BuildContext context) {
    return LxButton(
      title: context.s.guest_login_title,
      onTap: controller.guestLoginButtonOnTap,
      height: 30.w,
      buttonTypeCustomColor: ButtonTypeColor()
        ..backgroundColor = Colors.transparent
        ..borderColor = Colors.transparent
        ..textColor = LxCol.theme,
      buttonAlignmentEnum: ButtonAlignmentEnum.adaptive,
      fontWeightEnum: LxFontWeightEnum.bodyMedium,
    );
  }

  // 切换模式
  void _switchAuthMode(AuthMode mode) {
    controller.state.authMode.value = mode;
  }

  // 使用条款 / 隐私政策
  Widget _buildPolicyText() {
    return Padding(
      padding: EdgeInsets.only(top: 16.w),
      child: Wrap(
          alignment: WrapAlignment.center,
          crossAxisAlignment: WrapCrossAlignment.center,
          children: [
            TextButton(
              onPressed: () {
                // 打开使用条款
                webViewMixinPushTo(WebViewUrlType.userAgreement);
              },
              child: Text(
                local.user_agreement,
                style: TextStyle(
                  decoration: TextDecoration.none,
                  fontSize: 12,
                  color: LxCol.theme.withOpacity(0.8),
                ),
              ),
            ),
            Text(
              " | ",
              style: TextStyle(color: LxCol.theme.withOpacity(0.8)),
            ),
            TextButton(
              onPressed: () {
                // 打开隐私政策
                webViewMixinPushTo(WebViewUrlType.privacyPolicy);
              },
              child: Text(
                local.privacy_policy,
                style: TextStyle(
                  decoration: TextDecoration.none,
                  fontSize: 12,
                  color: LxCol.theme.withOpacity(0.8),
                ),
              ),
            ),
          ]),
    );
  }
}
